import { Component, ViewChild,OnInit,AfterContentInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { WizardComponent, NavigationMode } from 'angular-archwizard';
import { FormControl } from '@angular/forms';
import { DateAdapter } from '@angular/material/core';
import { RestService } from '../../services/rest.service';
import { TranslateService } from '@ngx-translate/core';

import * as _ from 'lodash';

@Component({
  selector: 'stepper-label-position-bottom-example',
  templateUrl: './person-content.component.html',
  styleUrls: ['./person-content.component.css']
})

export class PersonContentComponent implements OnInit {
  contentHeight = '85vh';
  person: any;

  fromTime;
  fromTimeCtrl = new FormControl(new Date());
  toTime;
  toTimeCtrl = new FormControl(new Date());
  error = '';

  chartOptions;
  echartsInstance;

  bchartOptions;
  bchartsInstance;

  hchartOptions;
  hchartsInstance;

  pchartOptions;
  pchartsInstance;

  schartOptions;
  schartsInstance;

  pageIndex:any;

  @ViewChild('wizard') public wizard: WizardComponent;

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<PersonContentComponent>,
              private adapter: DateAdapter<any>,
              private translate: TranslateService,
              private rest: RestService,
              private dialog: MatDialog) {
    switch (this.translate.currentLang) {
    case 'en':
      this.adapter.setLocale('en');
      break;
    case 'zh':
      this.adapter.setLocale('zh-CN');
      break;
    case 'tw':
    default:
      this.adapter.setLocale('zh-TW');
      break;
    }
    this.pageIndex = dialogData.pageIndex;

    this.person = dialogData.person;
    this.person.birth = this.dateformat(this.person.birth)
   // console.log(this.person)
   // this.initChart();
  }
  ngAfterContentInit() {
    //console.log(this.person)
    this.wizard.defaultStepIndex = this.pageIndex;
    this.wizard.navBarLocation =' ';
    this.wizard.disableNavigationBar =true;
  }
  dateformat(date)
  {
//shijianchuo是整数，否则要parseInt转换
    var time = new Date(date);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    // var s = time.getSeconds();
    //return this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm);//+':'+add0(s);
    return y+'-'+m+'-'+d;//+' '+h+':'+mm;//+':'+add0(s);
  }
  getTimeString(input) {
    if (input > 0) {
      return new Date(input).toLocaleString();
    }

    return '-';
  }
  initChart() {

    const options = {
     /* title: {
        x: 'left',
        y: 'top',
        text: '',
        subtext: '',
        subtextStyle: {color: 'black'},
      },*/
      tooltip : {
        trigger: 'item',
        axisPointer: {
          animation: false
        },
        formatter: (params) => {
          return this.translate.get('alarmingStarts')['value'] + ': ' + new Date(params.data[0]).toLocaleString() + '<br>' +
                 this.translate.get('alarmingAcked')['value'] + ': ' + (params.data[2] > 0 ? new Date(params.data[2]).toLocaleString() : '-');
        }
      },
      toolbox: {
        show: false,
        feature: {
          saveAsImage: {show: true, type: 'png'}
        }
      },
      calculable: false,
      grid: {
        x: '90',
        y: '20',
        x2: '20',
        y2: '0',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
      },
      yAxis: {
        type : 'value',
        splitArea: {show: true},
        name: '',
        axisLabel: {}
      },
      series: [{
        type: 'scatter',
        symbolSize: '10',
        showSymbol: false,
        markLine: {
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dashed',
                color: 'darkred'
              }
            }
          }
        },
        data: []
      }]
    };

   const bSubtext = this.translate.get('heartUnit')['value'];
    this.bchartOptions = _.cloneDeep(options);
   // this.bchartOptions.title.text = this.translate.get('breathe')['value'];
   // this.bchartOptions.title.subtext = bSubtext;
    this.bchartOptions.series[0].type = 'line';
    this.bchartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.breatheUp},
      {name: 'lower', yAxis: this.person.breatheLow},
    ];
    this.bchartOptions.tooltip.trigger = 'axis';
    this.bchartOptions.tooltip.formatter = (params) => {
      return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1] + ' ' + bSubtext;
    };

    this.hchartOptions = _.cloneDeep(options);
   // this.hchartOptions.title.text = this.translate.get('heart')['value'];
  //  this.hchartOptions.title.subtext = bSubtext;
    this.hchartOptions.series[0].type = 'line';
    this.hchartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];
    this.hchartOptions.tooltip.trigger = 'axis';
    this.hchartOptions.tooltip.formatter = (params) => {
      return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1] + ' ' + bSubtext;
    };

    const moveSubtext = this.translate.get('alarmUnit')['value'] + '/' + this.translate.get('hour')['value'];
    this.pchartOptions = _.cloneDeep(options);
   // this.pchartOptions.title.text = this.translate.get('sleep')['value'];
  //  this.pchartOptions.title.subtext = this.translate.get('hour')['value'];
    this.pchartOptions.tooltip.trigger = 'axis';
    this.pchartOptions.tooltip.formatter = null;
    this.pchartOptions.legend = { data: ['高压', '低压'] };
   // this.pchartOptions.xAxis = [{ type: 'category', data: [] }];
   // this.pchartOptions.yAxis = [{ type: 'value' }];
    this.pchartOptions.series = [{
      name: '高压',
      type: 'bar',
     // stack: 'sleep',
      barMaxWidth: 20,
      data: []
    }, {
      name: '低压',
      type: 'bar',
    //  stack: 'sleep',
      barMaxWidth: 20,
      data: []
    }];
    this.schartOptions = _.cloneDeep(options);
  // this.schartOptions.title.text = this.translate.get('sleep')['value'];
   // this.schartOptions.title.subtext = this.translate.get('hour')['value'];
    this.schartOptions.tooltip.trigger = 'axis';
    this.schartOptions.tooltip.formatter = null;
    this.schartOptions.legend = { data: ['餐后','餐前'] };
    //this.schartOptions.xAxis = [{ type: 'category', data: [] }];
    //this.schartOptions.yAxis = [{ type: 'value' }];
    this.schartOptions.series = [{
      name: '餐后',
      type: 'bar',
      //stack: 'sleep',
      barMaxWidth: 20,
      data: []
    }, {
      name: '餐前',
      type: 'bar',
      //stack: 'sleep',
      barMaxWidth: 20,
      data: []
    }];

 // console.log("init echarts");
  }

  onhChartInit(ec) {
  //  console.log("onhChartInit");
   // console.log(ec);
    this.hchartsInstance = ec;
    this.hchartsInstance.setOption(this.hchartOptions);
  }

  onbChartInit(ec) {
    this.bchartsInstance = ec;
    this.bchartsInstance.setOption(this.bchartOptions);
  }

  onpChartInit(ec) {
    this.pchartsInstance = ec;
    this.pchartsInstance.setOption(this.pchartOptions);
  }

  onsChartInit(ec) {
    this.schartsInstance = ec;
    this.schartsInstance.setOption(this.schartOptions);
  }
  buildEmptyData(startTime, endTime) {
    const data = [[startTime * 1000, ''], [endTime * 1000, '']];
    return data;
  }

  refresh() {
   /* let startTime = this.fromTimeCtrl.value ? this.fromTimeCtrl.value.setHours(0, 0, 0, 0) : null;
    let endTime = this.toTimeCtrl.value ? this.toTimeCtrl.value.setHours(23, 59, 59, 999) : null;

    if (!startTime) {
      this.error = 'noStartTime';
      return;
    }

    const currentTime = new Date().getTime();
    if (startTime > currentTime) {
      this.error = 'lateStartTime'
      return;
    }

    if ( !endTime || endTime > currentTime) {
      endTime = currentTime;
    }

    if (endTime < startTime) {
      this.error = 'startTimeGreaterThanEndTime'
      return;
    }

    this.error = '';

    startTime = Math.round(startTime / 1000);
    endTime = Math.round(endTime / 1000);

//    this.processType(startTime, endTime, 'HIST_MOVE', this.moveChartsInstance, this.moveChartOptions);
    this.processType(startTime, endTime, 'HIST_BREATHE', this.bchartsInstance, this.bchartOptions);
    this.processType(startTime, endTime, 'HIST_HEART', this.hchartsInstance, this.hchartOptions);

    this.processType(startTime, endTime, 'AWAY', this.awayAlarmChartsInstance, this.awayAlarmChartOptions);
    this.processType(startTime, endTime, 'SIDE', this.sideAlarmChartsInstance, this.sideAlarmChartOptions);
    this.processType(startTime, endTime, 'UP', this.upAlarmChartsInstance, this.upAlarmChartOptions);
    this.processType(startTime, endTime, 'BREATHE', this.breatheAlarmChartsInstance, this.breatheAlarmChartOptions);
    this.processType(startTime, endTime, 'HEART', this.heartAlarmChartsInstance, this.heartAlarmChartOptions);
    this.processType(startTime, endTime, 'WET', this.wetAlarmChartsInstance, this.wetAlarmChartOptions);

    this.processTurnOver(startTime, endTime);
    this.processSleep(startTime, endTime);*/
    const bendTime = new Date().getTime() ;/// 1000;
    const bstartTime = bendTime - 24 * 60 * 60 * 1000;
    const bstep = 5;
    // https://192.168.123.235/api/influx/getHeartHistory?devId=9510515034&start=1559529341000&end=1559615741000

    this.rest.getWithParams('api/influx/getHeartHistory', {
      //personId: this.person.id,
      devId:this.person.device2Id,//9510515034,
      start: bstartTime,//1559529341000,//
      end: bendTime,//1559615741000,//endTime,
      step: bstep,
      timeout: 4
    }).subscribe(resp => {
      let sData = resp;
      let pData =[];
      for (const key in sData) {
        if (sData.hasOwnProperty(key)) {
          const a = sData[key];
          pData.push(a);
        }
      }
      let heartData =[];
      let pressureHData = [];
      let pressureLData = [];
      let sugarData= [];
      for(var i=0;i<pData.length;i++){
        let tmpData = [];
        tmpData[0] = pData[i][0];
        tmpData[1] = pData[i][2];
        heartData.push(tmpData);
        let tmppData=[];
        tmppData[0] = pData[i][0];
        tmppData[1] = pData[i][3];
        pressureHData.push(tmppData);
        let tmplData=[];
        tmplData[0] = pData[i][0];
        tmplData[1] = pData[i][4];
        pressureLData.push(tmplData);
        let tmpsData = [];
        tmpsData[0] = pData[i][0];
        let stmp =6+Math.random();
        tmpsData[1] = Number(stmp).toFixed(1);
        sugarData.push(tmpsData);
      }

      if (heartData.length < 1){
        //this.hchartOptions.title.text = this.bTitle;
        //this.hchartOptions.title.textStyle.color = 'darkblue';
       // this.hchartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
        this.hchartsInstance.setOption(this.hchartOptions);
        return;
      }

      /* const data =  heartData;//['data']['result'][0].values;
       data.forEach(item => {
         console.log(item);
         item[0] = item[0] ;//* 1000;
       });*/
      this.hchartOptions.series[0].data = heartData;
      let currentValue = heartData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
     // this.hchartOptions.title.text = this.hTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);
    /*  if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
        this.hchartOptions.title.textStyle.color = 'darkred';
      } else {
        this.hchartOptions.title.textStyle.color = 'darkgreen';
      }*/
      this.hchartsInstance.setOption(this.hchartOptions);

      this.pchartOptions.series[0].data = pressureHData;
      this.pchartOptions.series[1].data = pressureLData;
      currentValue = pressureHData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
    //  this.pchartOptions.title.text = this.pTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);

      this.pchartsInstance.setOption(this.pchartOptions);

      this.schartOptions.series[0].data = sugarData;
      currentValue = sugarData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
     // this.schartOptions.title.text = this.sTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);

      this.schartsInstance.setOption(this.schartOptions);

    });

  }

  processType(startTime, endTime, alarm, chartInstance, chartOptions) {
    const type = this.rest.getAlarmEnumNumber(alarm);

    this.rest.getWithParams('api/elastic/typeInRange', {
      personId: this.person.id,
      startTime: startTime,
      endTime: endTime,
      type: type
    }).subscribe(resp => {
      let data: any = resp;
      if (data && data.length > 0) {
        if (data[0][0] !== startTime * 1000) {
          data.unshift([startTime * 1000, '']);
        }

        if (data[data.length - 1][0] !== endTime * 1000) {
          data.push([endTime * 1000, '']);
        }
      } else {
        data = this.buildEmptyData(startTime, endTime);
      }

      chartOptions.series[0].data = data;
      chartInstance.setOption(chartOptions);
    });
  }

  resizeChart() {
    if (this.hchartsInstance) {
      this.hchartsInstance.resize();
    }

    if (this.bchartsInstance) {
      this.bchartsInstance.resize();
    }
    if (this.pchartsInstance) {
      this.pchartsInstance.resize();
    }

    if (this.schartsInstance) {
      this.schartsInstance.resize();
    }
  }

  ngOnInit() {
    this.initChart();
    this.refresh();
    setTimeout(() => {
     // this.refresh();
    }, 1000);
  }
}
